package com.zego.example.videoplayerdemo.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.media.common.AVDescription;
import ohos.media.common.sessioncore.AVElement;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;

public class VideoElementManager {
    private static final String TAG = VideoElementManager.class.getSimpleName();
    private final List<AVElement> avElements = new ArrayList<>();

    public VideoElementManager(Context context) {
        loadAudioFromMediaLibrary(context);
        loadVideoFromMediaLibrary(context);
    }

    // 查找音频
    private void loadAudioFromMediaLibrary(Context context) {
        Uri audioUri = AVStorage.Audio.Media.EXTERNAL_DATA_ABILITY_URI;
        DataAbilityHelper helper = DataAbilityHelper.creator(context, audioUri, false);
        try {
            ResultSet resultSet = helper.query(audioUri, null, null);
            LogUtil.info(TAG, "The audio result size: " + resultSet.getRowCount());
            processResult(resultSet);
            resultSet.close();
        } catch (DataAbilityRemoteException e) {
            LogUtil.error(TAG, "Query system media failed.");
        } finally {
            helper.release();
        }
    }

    // 查找视频
    private void loadVideoFromMediaLibrary(Context context) {
        Uri videoUri = AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI;
        DataAbilityHelper helper = DataAbilityHelper.creator(context, videoUri, false);
        try {
            ResultSet resultSet = helper.query(videoUri, null, null);
            LogUtil.info(TAG, "The video result size: " + resultSet.getRowCount());
            processResult(resultSet);
            resultSet.close();
        } catch (DataAbilityRemoteException e) {
            LogUtil.error(TAG, "Query system media failed.");
        } finally {
            helper.release();
        }
    }

    // 处理数据到 List<AVElement>
    private void processResult(ResultSet resultSet) {
        while (resultSet.goToNextRow()) {
            String path = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.DATA));
            String title = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.AVBaseColumns.TITLE));
            AVDescription bean =
                    new AVDescription.Builder().setTitle(title).setIMediaUri(Uri.parse(path)).setMediaId(path).build();
            avElements.add(new AVElement(bean, AVElement.AVELEMENT_FLAG_PLAYABLE));
        }
    }

    public List<AVElement> getAvElements() {
        return avElements;
    }
}
